/**
 * 用于首次渲染修改渲染流程表单的数据
 * 仅针对 TYPE_MAP 里存在的类型
 *
 * TODO: 当复杂到一定程度，请及时拆分文件
 */
import React from 'react';
import { modifyConfig, modifyProps } from '@/pages/Flow/Mine/Apply/utils';
import moment from 'moment';
import request from '@/utils/request';

import TYPE_MAP from './consts';

const { ADD_GRADE_TYPE, ADD_GRADE, EDIT_GRADE, EDIT_GRADE_TYPE, REMOVE_GRADE, REMOVE_GRADE_TYPE } = TYPE_MAP;

function disabledDate(current) {
    return current && current < moment().endOf('day');
}

async function getCompanyNames() {
    // const result = await request('/api/org/v1/functional/list');
    const result = await request('/api/org/v1/functional/list', {
        method: 'POST',
        data: { organizationTypes: [1, 2], showTreeFlag: 1 }
    });
    if (result.code === 10000) {
        const [{ organizationName, children = [] }] = result.data;
        return [organizationName, ...children.map(item => item.organizationName)].join(',');
    }
    return '';
}

/**
 * @param {Props} props
 * @param {object} currentUser 当前用户信息
 * @param {string} type 表单类型，比如 addGradeType
 * @param {object} json 表单渲染源数据
 * @param {func} setJson 表单数据设置方法
 * @param {object} query URL 参数
 * @param {func} setPageLoading 用于设置页面是否加载，当需要额外请求数据的使用
 */
const useFinalJSON = props => {
    const { type, json, setJson, setPageLoading, templateLoading } = props;
    const { fields } = json;
    const finishedRef = React.useRef();
    React.useEffect(() => {
        if (templateLoading || finishedRef.current) {
            return;
        }

        // 默认关闭加载标识，当需要请求数据时开启。
        if (Object.values(TYPE_MAP).includes(type)) {
            setPageLoading(false);
        }

        const commonModify = async () => {
            let final = fields;
            const initialCompanyName = await getCompanyNames();
            final = modifyConfig('companyName', { initialValue: initialCompanyName }, final);
            final = modifyProps('companyName', { style: { width: 450 }, title: initialCompanyName }, final);
            final = modifyConfig('companyCode', { initialValue: 'ORG15540490989436999' }, final); // 默认集团
            final = modifyConfig('applyDate', { initialValue: moment().format('YYYY-MM-DD') }, final);
            final = modifyConfig('institutionName', { initialValue: '职级管理制度' }, final);
            final = modifyConfig('startTime', { initialValue: { time: moment().add(1, 'days'), unit: 4 } }, final);
            final = modifyProps('startTime', { disabledDate, style: { width: 150 } }, final);
            final = modifyConfig('releaseType', { initialValue: 'new' }, final);
            final = modifyConfig('auditEffectFlag', { initialValue: '0' }, final);
            final = modifyProps('companyCode', { style: { display: 'none' } }, final);
            final = modifyProps('gradeCode', { maxLength: 10 }, final);
            final = modifyConfig(
                'gradeCode',
                {
                    rules: [
                        {
                            required: false,
                            pattern: new RegExp(/^[A-Za-z0-9]+$/, 'g'),
                            message: '请输入正确的职级'
                        },
                        {
                            min: 2,
                            max: 10,
                            message: '职级限制2-10个字符！'
                        }
                    ],
                    getValueFromEvent: event => event.target.value.replace(/[^A-Za-z0-9]/g, '')
                },
                final
            );
            return final;
        };
        // 表单类型对应修改方法
        const processors = {
            async [ADD_GRADE_TYPE]() {
                const modifyFields = await commonModify();
                setJson({ ...json, fields: modifyFields });
            },
            async [ADD_GRADE]() {
                const modifyFields = await commonModify();
                setJson({ ...json, fields: modifyFields });
            },
            async [EDIT_GRADE]() {
                const modifyFields = await commonModify();
                setJson({ ...json, fields: modifyFields });
            },
            async [EDIT_GRADE_TYPE]() {
                const modifyFields = await commonModify();
                setJson({ ...json, fields: modifyFields });
            },
            async [REMOVE_GRADE]() {
                const modifyFields = await commonModify();
                setJson({ ...json, fields: modifyFields });
            },
            async [REMOVE_GRADE_TYPE]() {
                const modifyFields = await commonModify();
                setJson({ ...json, fields: modifyFields });
            }
        };
        const applyProcessor = async () => {
            const processor = processors[type];
            if (processor) {
                await processor(props);
                finishedRef.current = true;
            }
        };
        applyProcessor();
    }, [type, templateLoading]);
};

export default useFinalJSON;
